package com.taotao.search.service.ipml;

import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.Item;
import com.taotao.common.pojo.SearchResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.ExceptionUtil;
import com.taotao.search.dao.ISolrDao;
import com.taotao.search.mapper.ItemMapper;
import com.taotao.search.service.ISolrService;

@Service
public class SolrServiceIpml implements ISolrService {
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ISolrDao solrDao;

	@Autowired
	private SolrServer server;

	public TaotaoResult importAllItemsToSolr() {
		// TODO Auto-generated method stub
		try {
			List<Item> items = this.itemMapper.getItemList();
			for (Item item : items) {
				SolrInputDocument document = new SolrInputDocument();
				document.addField("id", item.getId());
				document.addField("item_sell_point", item.getSell_point());
				document.addField("item_price", item.getPrice());
				document.addField("item_title", item.getTitle());
				document.addField("item_image", item.getImage());
				document.addField("item_category_name", item.getCategory_name());
				document.addField("item_desc", item.getItem_desc());
				this.server.add(document);
			}
			server.commit();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
		return TaotaoResult.ok();
	}

	public SearchResult search(String queryString, int page, int rows)
			throws Exception {
		SolrQuery query = new SolrQuery();
		// 设置查询条件
		query.setQuery(queryString);
		// 设置开始页
		query.setStart((page - 1) * rows);
		// 每页的数量
		query.setRows(rows);
		// 设置默认搜查域
		query.set("df", "item_keywords");
		// 设置高亮
		query.setHighlight(true);
		// 添加高亮字段
		query.addHighlightField("item_title");
		// 设置高亮样式
		query.setHighlightSimplePre("<em style=\"color: red;\">");
		query.setHighlightSimplePost("</em>");
		SearchResult result = this.solrDao.search(query);
		result.setCurPage(page);
		long pageCount = result.getRecordCount() / rows;
		if (0 != result.getRecordCount() % rows) {
			pageCount++;
		}
		result.setPageCount(pageCount);
		return result;
	}
}
